package org.example.ams.service.impl.system;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.checkerframework.checker.units.qual.A;
import org.example.ams.dao.system.ISysUserDao;
import org.example.ams.entity.system.SecurityUser;
import org.example.ams.entity.system.SysUser;
import org.example.ams.service.system.ILoginService;
import org.example.ams.vo.LoginUser;
import org.example.common.api.CommonResult;
import org.example.security.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private ISysUserDao sysUserDao;


    @Override
    public CommonResult<String> login(LoginUser user) {
        Authentication inAuthentication = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword(),null);
        Authentication outAuthentication = authenticationManager.authenticate(inAuthentication);
        // 能走到这里说明认证成功，如果上一步认证失败，则会抛出UserNameNotFoundException/DisabledException/BadCredentialsException
        // 将登录状态存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(outAuthentication);
        // 生成token返回
        SecurityUser loginUser = (SecurityUser) outAuthentication.getPrincipal();
        loginUser.getSysUser().setPassword("");
        String token = jwtTokenUtil.generateToken(JSONUtil.toJsonStr(loginUser.getSysUser()));
        return CommonResult.success(token,"登录成功");
    }

    @Override
    public SysUser querySysUserByUserName(String username) {
        return sysUserDao.selectOne(new QueryWrapper<SysUser>().eq("username",username));
    }
}
